import React from 'react';
import { inject, observer } from 'mobx-react';
import { observable, action, toJS } from 'mobx';
import { routerShape } from 'react-router';
import { WeaErrorPage, WeaTools, WeaSearchGroup, WeaTop, WeaTab, WeaRightMenu, WeaLeftRightLayout, WeaDialog, WeaNewScroll } from 'ecCom';
import { Row,Button,Modal } from 'antd';
import MeetingDialog from '../../public/dialog/index';
import RoomPlanDialog from '../../public/roomPlan/index';
import moment from 'moment';
import CalViewTab from './calviewtab/index'
import LeftContainer from './leftcontainer/index'
import RightContainer from './rightcontainer/index'
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const errorModal = Modal.warning;

let _this = null;

@inject('meetingCalView')
@inject('meetingDialog')
@observer
class CalView extends React.Component {
	static contextTypes = {
		router: routerShape
	}
	constructor(props) {
		super(props);
		_this = this;
		this.state = {
			meetingType: 0,
			date: new Date(),
			meetingPerson: '',
			RoomPlanContainer: false,
			dialogType: 'preview',
			MeetingId: '',
			visible: false
		}
	}
	componentWillMount() {
		//一些初始化请求
		const { doInit } = this.props.meetingCalView;
		doInit();

	}

	componentDidMount() {
    window.meetingSetAll = this.setAll; // 满足无侵入开发新建或查看会议 2019-11-12
	}
	componentWillReceiveProps(nextProps) {
		let { doInit } = this.props.meetingCalView;
		if (this.props.location.key !== nextProps.location.key) {
			doInit()
		}

	}
	componentWillUnmount() {
		//组件卸载时一般清理一些状态
		let {meetingDialog} = this.props;
    meetingDialog.deleteForms();
    delete window.meetingSetAll; // 满足无侵入开发新建或查看会议 2019-11-12
	}

	render() {
		let { RoomPlanContainer, visible, dialogType, MeetingId } = this.state;
		const {meetingCalView } = this.props;
		let { status,canCreate, saveDate } = meetingCalView;
    let { loading, date} = status;
		const btns = [
			(canCreate&&<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i9yz16@btnClick`} type="primary" disabled={false} onClick={() => this.create('btnClick')}>{getLabel(383430,"新建会议")}</Button>),
			(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@luxtfc@meetingRoomReport`} type="primary" disabled={false} onClick={this.openMeetingRoomReport}>{getLabel(15881,"会议室使用情况")}</Button>)
		];
    let breadcrumb = this.getBreadcrumb()
    let collectParams={
			favname: getLabel(32483,"会议日历"),
			favouritetype: 5,
			objid: 0,
			importantlevel: 1,
    };
    let meeting_left_tree_visible = `meeting_left_tree_visible_${JSON.parse(localStorage.getItem('theme-account')) ? JSON.parse(localStorage.getItem('theme-account')).userid : ''}`;
		return (
			<div className="metting-calview" id="metting-calview-id">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@nfpp8n`} datas={this.getRightMenu()} onClick={this.onRightMenuClick}  collectParams={collectParams}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@tt07x0`}
            loading={loading}
            icon={<i className='icon-coms-meeting' />}
            iconBgcolor='#f14a2d'
            title={getLabel(32483,"会议日历")}
            buttons={btns}
            breadcrumb={breadcrumb}
            showDropIcon={true}
						dropMenuDatas={this.getRightMenu()}
						onDropMenuClick={this.onRightMenuClick}
						dropMenuProps={{collectParams: collectParams}}

          >
            <div style={{ overflowY: 'hidden', overflowX: 'auto', height: '100%' }}>
              <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ktlwwe`} className="metting-calview-left-right" style={{ minWidth: '700px', height: '100%' }}>
                <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@wmi3ca`}
                  className="meeting-calendar-left-right-layout"
                  leftWidth={210}
                  leftCom={<RightContainer ecId={`${this && this.props && this.props.ecId || ''}_RightContainer@73lav7`} setAll={this.setAll}/>}
                  showLeft={localStorage.getItem(meeting_left_tree_visible) !== 'true'}
					        onCollapse={(bool) => { localStorage.setItem(meeting_left_tree_visible, !bool); }}
                >
                  <LeftContainer ecId={`${this && this.props && this.props.ecId || ''}_LeftContainer@pf7928`} date={date} loading={loading} setAll={this.setAll}  >
                    <CalViewTab ecId={`${this && this.props && this.props.ecId || ''}_CalViewTab@8m41g2`} date={date} />
                  </LeftContainer>
                </WeaLeftRightLayout>
              </Row>
            </div>
          </WeaTop>
        </WeaRightMenu>
				
				<MeetingDialog ecId={`${this && this.props && this.props.ecId || ''}_MeetingDialog@90ft76`}
					setRoomPlan={this.setRoomPlan}
					setDialog={this.setDialog}
					setType={this.setType}
					setMeetingId={this.setMeetingId}
					setAll={this.setAll}
					type={dialogType}//新建为'create',查看为'preview',编辑'edit',会议决议'decision'
					visible={visible}//显隐受控
					doRefesh={this.doRefesh}//自定义刷新页面，不会关掉弹出框
					meetingId={MeetingId} //会议id，查看会议时用到
					isInterval={false}//新建会议类型，true是周期会议， false是普通会议
					meetingDate={date}//新建日期
				/>
        

				{RoomPlanContainer && <RoomPlanDialog ecId={`${this && this.props && this.props.ecId || ''}_RoomPlanDialog@p7xpbe`}
					setRoomPlan={this.setRoomPlan}
					meetingId={MeetingId}
					canCreate={false}
					height={600}
					width={1000}
					visible={RoomPlanContainer} />}
			</div>
		)
	}

	getBreadcrumb = ()=>{
    let {status, changeMeetingUserRoot} = this.props.meetingCalView
		let {meetingPersonName} = toJS(status)
		let breadcrumb = [
			{
				name: getLabel(32483,"会议日历"),
				onClick: () => {changeMeetingUserRoot(undefined,'','') },
			},
		];
		if(meetingPersonName){
			breadcrumb.push({
				name:`${meetingPersonName}${getLabel(387622,"的会议")}`,
				onClick: () => {},
			})
		}
		return breadcrumb 
	}

	setAll = (meetingId, bool, type) => {
    let { status } = this.props.meetingCalView
    let { onlyFlowCreate, hideCreateEntry, workflowBaseIds,date,requestFieldIds,beginTime,endTime } = toJS(status);
    let curmoment = moment(date).format("YYYY-MM-DD");
    let workflowBaseIdsArr = [];
    if(workflowBaseIds != ''){
      workflowBaseIdsArr = workflowBaseIds.split(',')
    }
    if(hideCreateEntry == 1 && type == 'create'){
      return;
    }else if(onlyFlowCreate == 1 && hideCreateEntry == 0 && type == 'create' && workflowBaseIdsArr.length == 1 ){
      
      let urlParamsTemp = [];
      requestFieldIds&&Object.keys(requestFieldIds).map((item)=>{
        if(item == 'begindate'){
          requestFieldIds.begindate&&requestFieldIds.begindate.map(item1=>{
            urlParamsTemp.push(`&${item1}=${curmoment}`)
          })
        }
        if(item == 'begintime'){
          requestFieldIds.begintime&&requestFieldIds.begintime.map(item1=>{
            urlParamsTemp.push(`&${item1}=${beginTime}`)
          })
        }
        if(item == 'enddate'){
          requestFieldIds.enddate&&requestFieldIds.enddate.map(item1=>{
            urlParamsTemp.push(`&${item1}=${curmoment}`)
          })
        }
        if(item == 'endtime'){
          requestFieldIds.endtime&&requestFieldIds.endtime.map(item1=>{
            urlParamsTemp.push(`&${item1}=${endTime}`)
          })
        }
        if(item == 'beginDateTime'){
          requestFieldIds.beginDateTime&&requestFieldIds.beginDateTime.map(item1=>{
            urlParamsTemp.push(`&${item1}=${curmoment} ${beginTime}`)
          })
        }
        if(item == 'endDateTime'){
          requestFieldIds.endDateTime&&requestFieldIds.endDateTime.map(item1=>{
            urlParamsTemp.push(`&${item1}=${curmoment} ${endTime}`)
          })
        }
      })
      window.open(`/spa/workflow/static4form/index.html#/main/workflow/req?iscreate=1&workflowid=${workflowBaseIds}${urlParamsTemp.join('')}`);
    }else if(onlyFlowCreate == 1 && hideCreateEntry == 0 && type == 'create' && workflowBaseIdsArr.length == 0){
      return errorModal({
        title: getLabel(15172, '系统提示'),
        content: getLabel(510148, '系统查找不到新建会议流程！'),
      })
    }else{
      this.setState({
        MeetingId: meetingId,
        visible: bool,
        dialogType: type
      })
    }
	}
	setMeetingId = (meetingId) => {
		this.setState({ MeetingId: meetingId })
	}
	setRoomPlan = (bool) => {
		this.setState({ RoomPlanContainer: bool })
	}
	setDialog = (bool) => {
		this.setState({ visible: bool })
	}
	setType = (type) => {
		this.setState({ dialogType: type })
	}

	doRefesh = () => {
		let { status, getData, getCalendarList,getNextMeeting ,isCalendar} = this.props.meetingCalView;
		let { type, meetingPerson, meetingType, date } = toJS(status);
		let curmoment = moment.isMoment(date) ? date : moment(date);
		let value = {
			selectUser: meetingPerson,
			selectdate: curmoment.format("YYYY-MM-DD"),
			meetingType: meetingType,//会议类型
		};
		getNextMeeting();
		type == 1 ||isCalendar? getData(value) : getCalendarList(value)
  }
  
	create = (clickType)=> {
    const {meetingCalView,type, meetingDialog } = this.props;
    let { saveDate, status } = meetingCalView;
    let { onlyFlowCreate, hideCreateEntry, workflowBaseIds,date,requestFieldIds,beginTime,endTime } = toJS(status);
    let curmoment = moment(date).format("YYYY-MM-DD");
    if(hideCreateEntry == 1){
      return;
    }else{
      let workflowBaseIdsArr = [];
      if(workflowBaseIds != ''){
        workflowBaseIdsArr = workflowBaseIds.split(',')
      }
      if(onlyFlowCreate == 1 && workflowBaseIdsArr.length == 1 ){
        let urlParamsTemp = [];
        requestFieldIds&&Object.keys(requestFieldIds).map((item)=>{
          if(item == 'begindate'){
            requestFieldIds.begindate&&requestFieldIds.begindate.map(item1=>{
              urlParamsTemp.push(`&${item1}=${curmoment}`)
            })
          }
          if(item == 'begintime'){
            requestFieldIds.begintime&&requestFieldIds.begintime.map(item1=>{
              urlParamsTemp.push(`&${item1}=${beginTime}`)
            })
          }
          if(item == 'enddate'){
            requestFieldIds.enddate&&requestFieldIds.enddate.map(item1=>{
              urlParamsTemp.push(`&${item1}=${curmoment}`)
            })
          }
          if(item == 'endtime'){
            requestFieldIds.endtime&&requestFieldIds.endtime.map(item1=>{
              urlParamsTemp.push(`&${item1}=${endTime}`)
            })
          }
          if(item == 'beginDateTime'){
            requestFieldIds.beginDateTime&&requestFieldIds.beginDateTime.map(item1=>{
              urlParamsTemp.push(`&${item1}=${curmoment} ${beginTime}`)
            })
          }
          if(item == 'endDateTime'){
            requestFieldIds.endDateTime&&requestFieldIds.endDateTime.map(item1=>{
              urlParamsTemp.push(`&${item1}=${curmoment} ${endTime}`)
            })
          }
        })
        window.open(`/spa/workflow/static4form/index.html#/main/workflow/req?iscreate=1&workflowid=${workflowBaseIds}${urlParamsTemp.join('')}`);
      }else if(onlyFlowCreate == 1 && hideCreateEntry == 0 && workflowBaseIdsArr.length == 0){
        return errorModal({
          title: getLabel(15172, '系统提示'),
          content: getLabel(510148, '系统查找不到新建会议流程！'),
        })
      }else{
        this.setState({ visible: true, dialogType: 'create', MeetingId:''});
        
      }
    }
    saveDate(new Date());
    clickType === 'btnClick' && meetingDialog.setState({ meeetingDateVisible: false });
  }

  openMeetingRoomReport = ()=> {
    const {meetingCalView } = this.props;
		meetingCalView.isMeetingUsageBtn = true;
		this.setState({ RoomPlanContainer: true })
  }
  
	getRightMenu() {
    const {meetingCalView } = this.props;
		let { canCreate } = meetingCalView;
    const rightBtns = [];
    canCreate&&rightBtns.push({ key: "new", content: getLabel(383430,"新建会议"), icon: <span className='icon-coms-New-Flow' /> })
    rightBtns.push({ key: "meetingRoomReport", content: getLabel(15881,"会议室使用情况"), icon: <span className='icon-coms-LargeArea' /> })
    return rightBtns;
	}
	onRightMenuClick = (key)=>{
    if(key == 'new'){
      this.create('btnClick');
    }else if(key == 'meetingRoomReport'){
      this.openMeetingRoomReport()
    }
	}
}

//打开附件
window.openMeetingDiscussDoc = (t, showid, meetingid) => {
	openFullWindowHaveBar(`/spa/document/index2file.jsp?id=${showid}&isOpenFirstAss=1&meetingid=${meetingid}`)
  }
//打开附件
window.openMeetingDiscussDownload = (t, showid, meetingid) => {
	window.open(`/weaver/weaver.file.FileDownload?fileid=${showid}&download=1&meetingid=${meetingid}`)
}

window.openMeetingAppLink = (linkType, linkid, meetingid, isPro=false) => {
	if (linkType == 'doc')
		window.open(`/spa/document/index.jsp?id=${linkid}&meetingid=${meetingid}`)
	else if (linkType == 'task')
		window.open(`/spa/prj/index.html#/main/prj/taskCard?taskid=${linkid}`)
	else if (linkType == 'crm')
		window.open(isPro?`/CRM/manage/customer/CustomerBaseView.jsp?CustomerID=${linkid}`:`/spa/crm/static/index.html#/main/crm/customerView?customerId=${linkid}`)
	else if (linkType == 'workflow')
		window.open(`/spa/workflow/static4form/index.html#/main/workflow/req?fromModul=meeting&modulResourceId=${meetingid}&requestid=${linkid}`)
	else if (linkType == 'project')
		window.open(`/spa/prj/index.html#/main/prj/projectCard?prjid=${linkid}`)
	else
		return false
}
 

export default CalView
